import { useCallback, useRef, useState } from "react";

export default function useMoveFu() {
  const [flag, setFlag] = useState(false);
  const [staX, setStaX] = useState(0);
  const [moveX, setMoveX] = useState(0);
  // pc端是否触发了滑动（避免和点击事件冲突）
  const [isPcMoveFlag, setIsPcMoveFlag] = useState(true);

  // 手指按住屏幕
  const touchstart = useCallback((x: number) => {
    setStaX(x);
    setFlag(true);
  }, []);

  // 手指移动事件
  const touchmove = useCallback(
    (x: number) => {
      if (flag) {
        setMoveX(x);
      }
    },
    [flag]
  );

  // pc端是否触发了滑动（避免和点击事件冲突）
  const time = useRef(-1);
  const isPcFu = useCallback(() => {
    clearTimeout(time.current);
    time.current = window.setTimeout(() => {
      setIsPcMoveFlag(true);
    }, 200);
  }, []);

  // 手指抬起事件
  const touchend = useCallback(
    (fu: (val: number) => void, dev: "pc" | "mobile") => {
      if (moveX !== 0) {
        if (staX > moveX && staX - moveX >= 20) {
          if (dev === "pc") setIsPcMoveFlag(false);
          fu(1);

          if (dev === "pc") isPcFu();
        } else if (moveX > staX && moveX - staX >= 20) {
          if (dev === "pc") setIsPcMoveFlag(false);
          fu(-1);
          if (dev === "pc") isPcFu();
        }
        setFlag(false);
        setStaX(0);
        setMoveX(0);
      }
    },
    [isPcFu, moveX, staX]
  );

  return {
    touchstart,
    touchmove,
    touchend,
    isPcMoveFlag,
  };
}
